package no.uials.distsys;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.rmi.*;
import java.rmi.registry.*;
import java.security.Permission;
import java.util.logging.*;

/**
 *
 * @author Anders & Martinsen
 */
public class Server {
    static boolean running = false;
    public final Dimension D = Toolkit.getDefaultToolkit().getScreenSize();
    private static final Logger LOG = Logger.getLogger(Server.class.getName());
    
    private Warehouse warehouse;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        if (!running) {
            new Server();
        }
    }
    
    /**
     * Starts a new RMI based server, and hard codes some test data into the system.
     */
    public Server() {
        System.out.println("Server starting...");
        
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager() {
                public void checkConnect(String host, int port) {}
                public void checkConnect(String host, int port, Object obj) {}
                public void checkAccept(String host, int port) {}
                public void checkPermission(Permission perm) {}
            });
        }
        
        DistSysSystem distSys = null;
        warehouse = new Warehouse();
        addUser(new User("user", "user", User.Role.USER));
        addUser(new User("anders", "anders", User.Role.USER));
        addUser(new User("admin", "admin", User.Role.ADMIN));
        warehouse.addArticle("Test", 399.99d, 5, 1, 2, 3);
        warehouse.addArticle("Article001", 49.50, 100, new Position(4, 12, 3));
        warehouse.addArticle("Article002", 499.50, 100, new Position(4, 12, 4));
        warehouse.addArticle("CD - In Flames - Sense Of Purpose", 149.90d, 3, new Position(2, 3, 1));
        try {
            Registry reg = null;
            try {
                reg = LocateRegistry.getRegistry();
                reg.list();
            } catch (RemoteException ex) {
                reg = LocateRegistry.createRegistry(1099);
            }
            distSys = new DistSysSystem(warehouse);
            
            reg.rebind(DistSysService.class.getName(), distSys);
            
            System.out.println("Server ready...");
        } catch (RemoteException ex) {
            LOG.log(Level.SEVERE, "Forbindelsen ble ikke opprettet.", ex);
        }
    }
    
    private void addUser(User user) {
        try {
            warehouse.addUser(user);
            System.out.println(user.getName() + " added.");
        } catch (DistSysException ex) {
            System.err.println(user.getName() + " not added.");
        }
    }
}